<?php
class Model_TableCategorie implements Model_ITable
{
	private static $con = null;
	private static $reqSelectAll = null;
	private static $reqSelectOne = null;
	private static $reqInsert = null;
	private static $reqDeleteOne = null;
	private static $reqUpdate = null;
        private static $reqCount = null;
	
	public static function setConnexion(MyPdo $pdo)
	{
		self::$con = $pdo;
	}
	
	public static function getConnexion()
	{
		return self::$con;
	}

	public static function init()
	{
		self::$reqSelectAll = self::$con->prepare('SELECT * FROM categorie ORDER BY id_categorie');
		self::$reqSelectOne = self::$con->prepare('SELECT * FROM categorie WHERE id_categorie = :idcond');
		self::$reqDeleteOne = self::$con->prepare('DELETE FROM categorie WHERE id_categorie = :idcond');
		self::$reqInsert = self::$con->prepare("INSERT INTO categorie VALUES(:id, :nom)");
		self::$reqUpdate = self::$con->prepare('UPDATE categorie SET nom = :nom WHERE id_categorie = :idcond');
                self::$reqCount = self::$con->prepare("SELECT COUNT(*) FROM categorie");
        }

	public static function fetchAll()
	{
		self::$reqSelectAll->execute();
		$results = self::$reqSelectAll->fetchAll();
		return $results;
	}

	public static function fetchOne($id)
	{
		self::$reqSelectOne->execute(array(':idcond' => $id));
		$results = self::$reqSelectOne->fetchAll();
		if( empty($results[0]) )
			return array();
		else
			return $results[0];
	}
	
	public static function delete($id)
	{
		self::$reqDeleteOne->execute(array(':idcond' => $id));
	}
	
	public static function insert($nom)
	{
            $id = slugify($nom);
            self::$reqInsert->execute(array(':id' => $id, ':nom' => $nom));
            return self::$con->lastInsertId();
	}
	
	public static function update($id, $nom)
	{
		self::$reqUpdate->execute(array(':nom' => $nom, ':idcond' => $id));
	}

        public static function count()
        {
            self::$reqCount->execute();
            return self::$reqCount->fetchColumn();
        }
}
